#include "event_loop_thread.h"

namespace rr {
namespace nio {

EventLoopThread::EventLoopThread(const std::string& name)
{

}

EventLoopThread::~EventLoopThread()
{

}

int32_t EventLoopThread::StartLoop()
{
    if(thread_.get()) {
        return 0;
    }

    thread_ = std::make_shared<std::thread>(&EventLoopThread::ThreadFunc, this);
    if(!thread_.get()) {
        return -1;
    }

    {
        std::unique_lock<std::mutex> lock(mutex_);
        while(!loop_.get()) {
            cond_.wait(lock);
        }
    }

    return 0;
}

void EventLoopThread::StopLoop()
{
    if(loop_.get()) {
        loop_->Quit();
    }

    if(thread_.get()) {
        if(thread_->joinable()) {
            thread_->join();
        }
        thread_ = nullptr;
    }

    return;
}

void EventLoopThread::ThreadFunc()
{   
    // todo set thread name
    {
        std::lock_guard<std::mutex> lock(mutex_);
        loop_ = std::make_shared<EventLoop>();

        if(init_cb_) {
            init_cb_(loop_);
        }

        cond_.notify_all();
    }

    loop_->Loop();

    if(exit_cb_) {
        exit_cb_(loop_);
    }

    return;
}

} //namespace 
} //namespace 
